﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;

namespace TugasAkhir.Helpers
{
    public sealed class RTabel
    {
        private static RTabel instance;

        public static RTabel Instance
        {
            get
            {
                if (instance == null)
                    instance = new RTabel();
                return instance;
            }
        }

        private Dictionary<int, double> data;
        private string path;

        public double this[int key]
        {
            get
            {
                return GetValue(key);
            }
        }

        private RTabel()
        {
            this.data = new Dictionary<int, double>();
            this.path = string.Empty;
        }

        public void SetPath(string path)
        {
            var items = File.ReadAllLines(path);
            foreach (string s in items)
            {
                string[] split = s.Split(new char[] { ',' });
                if (!this.data.ContainsKey(int.Parse(split[0])))
                this.data.Add(int.Parse(split[0]), double.Parse(split[1]));
            }
        }

        public double GetValue(int key)
        {
            if (this.data.ContainsKey(key))
            {
                return this.data[key];
            }
            else
            {
                int max = FindMax(key);
                int min = FindMin(key);

                double l = (this.data[min] - this.data[max]) / ((double)max - (double)min) * ((double)key - (double)min);

                return this.data[min] - l;
            }
        }

        private int FindMax(int key)
        {
            int flag = key;
            while (flag <= this.data.Keys.Last())
            {
                if (this.data.ContainsKey(flag))
                {
                    break;
                }
                flag++;
            }
            return flag;
        }

        private int FindMin(int key)
        {
            int flag = key;
            while (flag >= this.data.Keys.First())
            {
                if (this.data.ContainsKey(flag))
                {
                    break;
                }
                flag--;
            }
            return flag;
        }
    }
}